package com.demo.demo1;

import java.util.Collection;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class PhoneSelectActivity extends ActionBarActivity {

	PhoneSelectFragment phoneSelectFragment;
	
	private final IntentFilter intentFilter = new IntentFilter();	
	private  WifiP2pManager manager;
    private  Channel channel;
    
	private BroadcastReceiver receiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_phone_select);

		if (savedInstanceState == null) {
			phoneSelectFragment = new PhoneSelectFragment();
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, phoneSelectFragment).commit();
		}
		startPhoneSearch();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.phone_select, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PhoneSelectFragment extends Fragment implements PeerListListener{

		private ListView listView;
		private ArrayAdapter<String> listViewadapter;

		public PhoneSelectFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_phone_select,
					container, false);
			listView = (ListView) rootView.findViewById(R.id.listView1);
			listViewadapter = new ArrayAdapter<String>(rootView.getContext(),
					android.R.layout.simple_list_item_single_choice);
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
			listView.setAdapter(listViewadapter);

			Toast.makeText(getActivity(), "Finding phones...",
					Toast.LENGTH_LONG).show();
			
			return rootView;
		}

		
		
		public void send(){
			String selectedPhone=null;
			String[] selectedFiles=(String[]) getActivity().getIntent().getExtras().get("selectedItems");//TODO type check
				SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
				for (int i = 0; i < checkedItemPositions.size(); i++) {
					if(checkedItemPositions.valueAt(i)){
						selectedPhone = (String) listView.getItemAtPosition(checkedItemPositions.keyAt(i));
						break;
					}
				}			
				//TODO send. seperate process
				Toast.makeText(getActivity()," Sending "+selectedFiles+" to "+selectedPhone, Toast.LENGTH_LONG).show();
			
			
		}

		@Override
		public void onPeersAvailable(WifiP2pDeviceList peers) {
			if (listViewadapter != null) {
				listViewadapter.clear();
				Collection<WifiP2pDevice> deviceList = peers.getDeviceList();
				for(WifiP2pDevice device:deviceList){
					listViewadapter.add(device.deviceAddress);
				}
			}
		}
	}

	public void refreshPhonesOnClick() {
			findPhones();
	}
	
	public void sendOnClick(View view){
		if(phoneSelectFragment!=null){
			phoneSelectFragment.send();
		}
	}
	
	private void findPhones() {
		manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {

            @Override
            public void onSuccess() {
                Toast.makeText(PhoneSelectActivity.this, "Discovery Initiated",
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int reasonCode) {
                Toast.makeText(PhoneSelectActivity.this, "Discovery Failed : " + reasonCode,
                        Toast.LENGTH_SHORT).show();
            }
        });			
	}
	
	private void startPhoneSearch(){
		intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);

        manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        channel = manager.initialize(this, getMainLooper(), null);        
        
        receiver = new BroadcastReceiver() {			
			@Override
			public void onReceive(Context context, Intent intent) {
				 String action = intent.getAction();
			        if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
			            int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
			            if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
			              
			            } else {
			               Toast.makeText(PhoneSelectActivity.this, "WiFi is off", Toast.LENGTH_SHORT).show();
			            }
			        } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {

			            // request available peers from the wifi p2p manager. This is an
			            // asynchronous call and the calling activity is notified with a
			            // callback on PeerListListener.onPeersAvailable()
			            if (manager != null) {
			                manager.requestPeers(channel, (PeerListListener) phoneSelectFragment);
			            }
			        } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {

			            if (manager == null) {
			                return;
			            }

			            NetworkInfo networkInfo = (NetworkInfo) intent
			                    .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);

			            if (networkInfo.isConnected()) {

			                // we are connected with the other device, request connection
			                // info to find group owner IP
			            	Toast.makeText(PhoneSelectActivity.this, "connected to "+ networkInfo.getTypeName(), Toast.LENGTH_SHORT).show();
//			                DeviceDetailFragment fragment = (DeviceDetailFragment) activity
//			                        .getFragmentManager().findFragmentById(R.id.frag_detail);
//			                manager.requestConnectionInfo(channel, fragment);
			            } else {
			                // It's a disconnect
			              
			            }
			        } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
//			            DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
//			                    .findFragmentById(R.id.frag_list);
//			            fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
//			                    WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
			        	//TODO ???
			        	Toast.makeText(PhoneSelectActivity.this, "this device changed !!", Toast.LENGTH_SHORT).show();

			        }
				
			}
		};
		
		findPhones();
	}

}
